package com.chuji.crmcj.act;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.bean.MagClientLoseDetailInfo;
import com.chuji.crmcj.bean.RejectToSalesInfo;
import com.chuji.crmcj.utils.CommonUtil;
import com.chuji.crmcj.utils.NumberUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MagOrderLoseDetailActivity extends BaseActivity implements View.OnClickListener {
    //回退
    private ImageView mIv_Back;
    //数据存储
    List<MagClientLoseDetailInfo.ApiParamObjEntity> magClientLoseDetailData;
    //网络数据
    private MagClientLoseDetailInfo magClientLoseDetailInfo;
    private Context context;
    //驳回销售员列表数据
    private List<RejectToSalesInfo.ApiParamObjEntity> rejectToSalesData;
    //驳回销售员列表网络数据
    private RejectToSalesInfo rejectToSalesInfo;
    //客户头像
    private ImageView mIv_client_head;
    //客户姓名
    private TextView mTv_client_name;
    //客户电话
    private TextView mTv_client_phoneNumber;
    //意向车型
    private TextView mTv_car_type;
    //确认战败
    private LinearLayout ll_redeal;
    //驳回
    private LinearLayout ll_reject;
    //客户等级
    private ImageView mIv_level;
    //销售员名字
    private TextView mTv_sales_name;
    //最后联系时间
    private TextView mTv_last_time;
    //战败原因内容
    private TextView mTv_lose_reason;
    //备注内容
    private TextView mTv_remarks;
    //签订订单时间
    private TextView mTv_order_sign_time;
    //订单车型
    private TextView mTv_order_car_type;
    //订单配置
    private TextView mTv_order_configure;
    //订单颜色
    private TextView mTv_car_color;
    //成交金额
    private TextView mTv_deal_money;
    //交车日期
    private TextView mTv_get_date;
    //付款方式
    private TextView mTv_pay_type;
    //车架号
    private TextView mTv_frame;
    //购买方式
    private TextView mTv_buy_way;
    //车主名
    private TextView mTv_car_user_name;
    //身份证号
    private TextView mTv_id_card;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mag_order_lose_detail);
        //初始化组件
        mIv_Back = (ImageView) findViewById(R.id.iv_Back);
        mIv_client_head = (ImageView) findViewById(R.id.iv_client_head);
        mTv_client_name = (TextView) findViewById(R.id.tv_client_name);
        mTv_client_phoneNumber = (TextView) findViewById(R.id.tv_client_phoneNumber);
        mTv_car_type = (TextView) findViewById(R.id.tv_car_type);
        ll_redeal = (LinearLayout) findViewById(R.id.ll_redeal);
        ll_reject = (LinearLayout) findViewById(R.id.ll_reject);
        mIv_level = (ImageView) findViewById(R.id.iv_level);
        mTv_sales_name = (TextView) findViewById(R.id.tv_sales_name);
        mTv_last_time = (TextView) findViewById(R.id.tv_last_time);
        mTv_order_sign_time = (TextView) findViewById(R.id.tv_order_sign_time);
        mTv_order_car_type = (TextView) findViewById(R.id.tv_order_car_type);
        mTv_order_configure = (TextView) findViewById(R.id.tv_order_configure);
        mTv_car_color = (TextView) findViewById(R.id.tv_car_color);
        mTv_deal_money = (TextView) findViewById(R.id.tv_deal_money);
        mTv_get_date = (TextView) findViewById(R.id.tv_get_date);
        mTv_pay_type = (TextView) findViewById(R.id.tv_pay_type);
        mTv_frame = (TextView) findViewById(R.id.tv_frame);
        mTv_buy_way = (TextView) findViewById(R.id.tv_buy_way);
        mTv_car_user_name = (TextView) findViewById(R.id.tv_car_user_name);
        mTv_id_card = (TextView) findViewById(R.id.tv_id_card);
        mTv_lose_reason = (TextView) findViewById(R.id.tv_lose_reason);
        mTv_remarks = (TextView) findViewById(R.id.tv_remarks);
        //数据
        initDa();
        //设置点击事件
        mIv_Back.setOnClickListener(this);
        ll_redeal.setOnClickListener(this);
        ll_reject.setOnClickListener(this);
    }
    public void initDa() {
        /**
         * 获得订单战败信息
         */
        getAppraiseData();
    }
    private void getAppraiseData() {
        //第一次
        if (magClientLoseDetailData == null) {
            magClientLoseDetailData = new ArrayList<MagClientLoseDetailInfo.ApiParamObjEntity>();
        }
        requestData();
    }
    private void requestData() {
        //初始化Volley
        String strURL = String.format(UrlUtils.GET_MAG_ORDER_LOSE_DETAIL+"&UserID="+"1227FC37-8E05-43ED-BE86-0CE5A401FD6F"+"&defeatType=1"+"&DefeatApproveID="+"A66E7450-01B9-46E6-A391-898DB84C7413");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                magClientLoseDetailInfo = JSON.parseObject(response, MagClientLoseDetailInfo.class);
                magClientLoseDetailData.addAll(magClientLoseDetailInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        for(int i=0;i<magClientLoseDetailData.size();i++) {
                            mTv_client_name.setText(magClientLoseDetailData.get(i).getCustomerName());
                            mTv_car_type.setText(magClientLoseDetailData.get(i).getBargainType());
                            mTv_client_phoneNumber.setText(NumberUtils.parsePhoneNumber(magClientLoseDetailData.get(i).getCustormerTel()));
                            mTv_sales_name.setText(magClientLoseDetailData.get(i).getSaleName());
                            mTv_last_time.setText(magClientLoseDetailData.get(i).getCreateTime());
                            mTv_lose_reason.setText(magClientLoseDetailData.get(i).getDefeatReason());
                            mTv_remarks.setText(magClientLoseDetailData.get(i).getDefeatcomment());
                            //判断客户等级
                            mIv_level.setImageDrawable(CommonUtil.getLevelIcon(magClientLoseDetailData.get(i).getCustomerLevel()));

                            mTv_order_sign_time.setText(magClientLoseDetailData.get(i).getOrderCreateTime());
                            mTv_order_car_type.setText(magClientLoseDetailData.get(i).getCarModel());
                            mTv_order_configure.setText(magClientLoseDetailData.get(i).getCarConfiguration());
                            mTv_car_color.setText(magClientLoseDetailData.get(i).getCarColor());
                            BigDecimal bd=new BigDecimal(magClientLoseDetailData.get(i).getAmount());
                            mTv_deal_money.setText(NumberUtils.parseMoney(",###,###", bd));
                            mTv_get_date.setText(magClientLoseDetailData.get(i).getDeliveryTime());
                            mTv_pay_type.setText(magClientLoseDetailData.get(i).getPaymentType());
                            mTv_frame.setText(magClientLoseDetailData.get(i).getVIN());
                            mTv_buy_way.setText(magClientLoseDetailData.get(i).getBargainType());
                            mTv_car_user_name.setText(magClientLoseDetailData.get(i).getUserName());
                            mTv_id_card.setText(magClientLoseDetailData.get(i).getCard());
                        }
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    public void onClick(View view) {
        switch(view.getId()) {
            case R.id.ll_redeal:
                showLoseClientDialog();
                break;
            case R.id.ll_reject:
                showSalesDialog();
                break;
            case R.id.iv_Back:
                finish();
                break;
        }
    }
    //自定义dialog
    private void showLoseClientDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_mag_client_lose, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        final TextView mTvFolType = (TextView) view.findViewById(R.id.tv_isfollow);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UIUtils.showToastSafe("已确认战败");
                dialog.dismiss();
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
    private void showSalesDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_reject_apply, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        ListView lv_checkBox= (ListView) view.findViewById(R.id.lv_checkBox);
        if (rejectToSalesData == null) {
            rejectToSalesData = new ArrayList<RejectToSalesInfo.ApiParamObjEntity>();
        }
        SalesAdapter adapter=new SalesAdapter();
        lv_checkBox.setAdapter(adapter);
        lv_checkBox.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                UIUtils.showToastSafe("选中了"+i+"的"+rejectToSalesData.get(i));
            }
        });
        lv_checkBox.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UIUtils.showToastSafe("已驳回");
                //得到选中的数据并发送

                dialog.dismiss();
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
    class SalesAdapter extends BaseAdapter {

        //销售员头像
        private ImageView iv_sales_head;
        //销售员名字
        private TextView tv_device_name;
        HashMap<String, Boolean> states = new HashMap<String, Boolean>();//用于记录每个RadioButton的状态，并保证只可选一个

        @Override
        public int getCount() {
            return rejectToSalesData.size();
        }

        @Override
        public Object getItem(int position) {
            return rejectToSalesData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(context).inflate(R.layout.dialog_reject_to_sales, null);
            iv_sales_head=(ImageView) convertView.findViewById(R.id.iv_sales_head);
            tv_device_name= (TextView) convertView.findViewById(R.id.tv_device_name);
            RadioButton rdBtn;
            if (rejectToSalesData == null) {
                rejectToSalesData = new ArrayList<RejectToSalesInfo.ApiParamObjEntity>();
            }
                //初始化Volley
                String strURL = String.format(UrlUtils.GET_MAG_REJECT_SALES+"&UserID="+"1227FC37-8E05-43ED-BE86-0CE5A401FD6F"+"&DefeatApproveID="+"A66E7450-01B9-46E6-A391-898DB84C7413");
                StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        rejectToSalesInfo = JSON.parseObject(response, RejectToSalesInfo.class);
                        rejectToSalesData.addAll(rejectToSalesInfo.getApiParamObj());
                        UIUtils.runInMainThread(new Runnable() {
                            @Override
                            public void run() {
                                iv_sales_head.setImageResource(R.drawable.icon01);
                                if(rejectToSalesData.get(0).getOriginal().equals(1)) {
                                    tv_device_name.setText(rejectToSalesData.get(0).getRealName()+"(原负责人)");
                                }
                            }
                        });
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        System.out.println("失败" + error);
                        UIUtils.showToastSafe("请检查网络");
                    }
                });
                // Add the request to the RequestQueue.
                VolleyUtil.getRequestQueue().add(stringRequest);
            final RadioButton radio = (RadioButton) convertView.findViewById(R.id.radio_btn);
            rdBtn = radio;
            //当RadioButton被选中时，将其状态记录进States中，并更新其他RadioButton的状态使它们不被选中
            rdBtn.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    if(position==1){
                        radio.isChecked();
                    }
                    //重置，确保最多只有一项被选中
                    for (String key : states.keySet()) {
                        states.put(key, false);
                    }
                    states.put(String.valueOf(position), radio.isChecked());
                    UIUtils.showToastSafe("选中了" + position + "的" + rejectToSalesData.get(position));
                    SalesAdapter.this.notifyDataSetChanged();
                }
            });
            boolean res = false;
            if (states.get(String.valueOf(position)) == null || states.get(String.valueOf(position)) == false) {
                res = false;
                states.put(String.valueOf(position), false);
            } else
                res = true;
            rdBtn.setChecked(res);
            return convertView;
        }
    }
}
